import React, { useState, useEffect } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import { cn } from '@/lib/utils';
import { toast } from '@/lib/toast-with-audio';

// 用户接口定义
interface User {
  id: number;
  username: string;
  name: string;
  email: string;
  role: string;
  status: number; // 0-停用, 1-启用
  lastLogin: string;
  avatar: string | null;
  userType: 'super_admin' | 'org_admin' | 'normal_user';
  password?: string;
  organization?: string;
  phone?: string;
  department?: string;
  position?: string;
}

interface UserDrawerProps {
  isOpen: boolean;
  onClose: () => void;
  user: User | null;
  mode: 'view' | 'edit' | 'create';
  onSave: (userData: Partial<User>) => void;
  className?: string;
}

const UserDrawer: React.FC<UserDrawerProps> = ({
  isOpen,
  onClose,
  user,
  mode,
  onSave,
  className = ''
}) => {
  const [formData, setFormData] = useState<Partial<User>>({});
  const [isEditing, setIsEditing] = useState(mode === 'create' || mode === 'edit');
  const [avatarFile, setAvatarFile] = useState<File | null>(null);
  const [avatarPreview, setAvatarPreview] = useState<string>('');
  const [showPassword, setShowPassword] = useState(false);

  // 初始化表单数据
  useEffect(() => {
    if (user) {
      setFormData({
        ...user,
        password: '' // 编辑时不显示密码
      });
      if (user.avatar) {
        setAvatarPreview(user.avatar);
      }
    } else if (mode === 'create') {
      setFormData({
        username: '',
        name: '',
        email: '',
        role: '开发工程师',
        status: 1,
        userType: 'normal_user',
        password: '123456', // 默认密码
        organization: '',
        phone: '',
        department: '',
        position: ''
      });
      setAvatarPreview('');
    }
    setIsEditing(mode === 'create' || mode === 'edit');
  }, [user, mode]);

  // 处理表单输入变化
  const handleInputChange = (field: keyof User, value: any) => {
    setFormData(prev => ({
      ...prev,
      [field]: value
    }));
  };

  // 处理头像上传
  const handleAvatarChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (file) {
      // 验证文件类型
      if (!file.type.startsWith('image/')) {
        toast('请选择图片文件');
        return;
      }
      
      // 验证文件大小（限制为2MB）
      if (file.size > 2 * 1024 * 1024) {
        toast('图片大小不能超过2MB');
        return;
      }
      
      setAvatarFile(file);
      
      // 创建预览
      const reader = new FileReader();
      reader.onload = (e) => {
        setAvatarPreview(e.target?.result as string);
      };
      reader.readAsDataURL(file);
    }
  };

  // 生成随机密码
  const generateRandomPassword = () => {
    const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*';
    let password = '';
    for (let i = 0; i < 12; i++) {
      password += chars.charAt(Math.floor(Math.random() * chars.length));
    }
    setFormData({ ...formData, password });
    setShowPassword(true); // 生成密码后显示明文
  };

  // 重置密码
  const resetPassword = () => {
    handleInputChange('password', '123456');
    setShowPassword(true); // 重置密码后显示明文
    toast('密码已重置为默认值');
  };

  // 保存用户信息
  const handleSave = () => {
    // 表单验证
    if (!formData.username?.trim()) {
      toast('请输入用户名');
      return;
    }
    if (!formData.name?.trim()) {
      toast('请输入姓名');
      return;
    }
    if (!formData.email?.trim()) {
      toast('请输入邮箱');
      return;
    }
    if (mode === 'create' && !formData.password?.trim()) {
      toast('请输入密码');
      return;
    }

    // 处理头像上传
    if (avatarFile) {
      // 这里应该调用上传API，暂时用base64模拟
      // 实际项目中应该上传到服务器并获取URL
      const reader = new FileReader();
      reader.onload = (e) => {
        const avatarData = e.target?.result as string;
        onSave({
          ...formData,
          avatar: avatarData
        });
      };
      reader.readAsDataURL(avatarFile);
    } else {
      onSave(formData);
    }
  };

  // 获取用户类型显示名称
  const getUserTypeDisplay = (type: string) => {
    switch (type) {
      case 'super_admin': return '超级管理员';
      case 'org_admin': return '机构管理员';
      case 'normal_user': return '普通人员';
      default: return type;
    }
  };

  // 获取用户类型选项
  const userTypeOptions = [
    { value: 'super_admin', label: '超级管理员' },
    { value: 'org_admin', label: '机构管理员' },
    { value: 'normal_user', label: '普通人员' }
  ];

  // 角色选项
  const roleOptions = [
    '超级管理员', '项目经理', '开发工程师', '测试工程师', '产品经理'
  ];

  if (!isOpen) return null;

  return (
    <AnimatePresence>
      {isOpen && (
        <motion.div
          className="fixed inset-0 z-50 overflow-hidden"
          initial={{ opacity: 0 }}
          animate={{ opacity: 1 }}
          exit={{ opacity: 0 }}
          transition={{ duration: 0.2 }}
          onClick={onClose}
        >
          <motion.div
            className="absolute inset-0 bg-gray-600 bg-opacity-75 transition-opacity"
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            exit={{ opacity: 0 }}
            transition={{ duration: 0.2 }}
          />
          <div className="absolute inset-0 overflow-hidden">
            <div className="absolute inset-y-0 right-0 flex max-w-full">
              <motion.div
                className={cn(
                  'relative w-screen max-w-2xl bg-white shadow-xl dark:bg-gray-900',
                  className
                )}
                initial={{ x: '100%' }}
                animate={{ x: 0 }}
                exit={{ x: '100%' }}
                transition={{ type: 'tween', duration: 0.3 }}
                onClick={(e) => e.stopPropagation()}
              >
                {/* 抽屉头部 */}
                <div className="flex items-center justify-between p-6 border-b border-gray-200 dark:border-gray-700">
                  <div className="flex items-center space-x-3">
                    <div className="w-10 h-10 rounded-full bg-blue-100 dark:bg-blue-900 flex items-center justify-center">
                      <i className="fa-solid fa-user text-blue-600 dark:text-blue-400 text-lg"></i>
                    </div>
                    <h3 className="text-lg font-semibold text-gray-900 dark:text-white">
                      {mode === 'create' ? '新建用户' : mode === 'edit' ? '编辑用户' : '用户详情'}
                    </h3>
                  </div>
                  <button
                    type="button"
                    className="rounded-md text-gray-400 hover:text-gray-500 focus:outline-none"
                    onClick={onClose}
                  >
                    <i className="fa-solid fa-times text-xl"></i>
                  </button>
                </div>

                {/* 抽屉内容 */}
                <div className="p-6 overflow-y-auto h-[calc(100vh-12rem)]">
                  {/* 头像上传区域 */}
                  <div className="mb-6">
                    <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-3">
                      用户头像
                    </label>
                    <div className="flex items-center space-x-4">
                      <div className="relative">
                        {avatarPreview ? (
                          <img
                            src={avatarPreview}
                            alt="头像预览"
                            className="w-20 h-20 rounded-full object-cover border-2 border-gray-300"
                          />
                        ) : (
                          <div className="w-20 h-20 rounded-full bg-gray-200 flex items-center justify-center border-2 border-gray-300">
                            <i className="fa-solid fa-user text-gray-400 text-2xl"></i>
                          </div>
                        )}
                        {isEditing && (
                          <label className="absolute bottom-0 right-0 bg-blue-600 text-white p-1 rounded-full cursor-pointer hover:bg-blue-700">
                            <i className="fa-solid fa-camera text-xs"></i>
                            <input
                              type="file"
                              accept="image/*"
                              className="hidden"
                              onChange={handleAvatarChange}
                            />
                          </label>
                        )}
                      </div>
                      {isEditing && (
                        <div className="text-sm text-gray-500">
                          <p>支持 JPG、PNG 格式</p>
                          <p>图片大小不超过 2MB</p>
                        </div>
                      )}
                    </div>
                  </div>

                  {/* 基本信息表单 */}
                  <div className="grid grid-cols-1 md:grid-cols-2 gap-4 mb-6">
                    <div>
                      <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                        用户名 <span className="text-red-500">*</span>
                      </label>
                      {isEditing ? (
                        <input
                          type="text"
                          value={formData.username || ''}
                          onChange={(e) => handleInputChange('username', e.target.value)}
                          className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 dark:bg-gray-800 dark:border-gray-600 dark:text-white"
                          placeholder="请输入用户名"
                        />
                      ) : (
                        <div className="px-3 py-2 bg-gray-50 dark:bg-gray-800 rounded-lg text-gray-900 dark:text-white">
                          {formData.username}
                        </div>
                      )}
                    </div>

                    <div>
                      <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                        姓名 <span className="text-red-500">*</span>
                      </label>
                      {isEditing ? (
                        <input
                          type="text"
                          value={formData.name || ''}
                          onChange={(e) => handleInputChange('name', e.target.value)}
                          className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 dark:bg-gray-800 dark:border-gray-600 dark:text-white"
                          placeholder="请输入姓名"
                        />
                      ) : (
                        <div className="px-3 py-2 bg-gray-50 dark:bg-gray-800 rounded-lg text-gray-900 dark:text-white">
                          {formData.name}
                        </div>
                      )}
                    </div>

                    <div>
                      <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                        邮箱 <span className="text-red-500">*</span>
                      </label>
                      {isEditing ? (
                        <input
                          type="email"
                          value={formData.email || ''}
                          onChange={(e) => handleInputChange('email', e.target.value)}
                          className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 dark:bg-gray-800 dark:border-gray-600 dark:text-white"
                          placeholder="请输入邮箱"
                        />
                      ) : (
                        <div className="px-3 py-2 bg-gray-50 dark:bg-gray-800 rounded-lg text-gray-900 dark:text-white">
                          {formData.email}
                        </div>
                      )}
                    </div>

                    <div>
                      <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                        手机号
                      </label>
                      {isEditing ? (
                        <input
                          type="tel"
                          value={formData.phone || ''}
                          onChange={(e) => handleInputChange('phone', e.target.value)}
                          className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 dark:bg-gray-800 dark:border-gray-600 dark:text-white"
                          placeholder="请输入手机号"
                        />
                      ) : (
                        <div className="px-3 py-2 bg-gray-50 dark:bg-gray-800 rounded-lg text-gray-900 dark:text-white">
                          {formData.phone || '未设置'}
                        </div>
                      )}
                    </div>

                    <div>
                      <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                        用户类型
                      </label>
                      {isEditing ? (
                        <select
                          value={formData.userType || 'normal_user'}
                          onChange={(e) => handleInputChange('userType', e.target.value)}
                          className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 dark:bg-gray-800 dark:border-gray-600 dark:text-white"
                        >
                          {userTypeOptions.map(option => (
                            <option key={option.value} value={option.value}>
                              {option.label}
                            </option>
                          ))}
                        </select>
                      ) : (
                        <div className="px-3 py-2 bg-gray-50 dark:bg-gray-800 rounded-lg text-gray-900 dark:text-white">
                          {getUserTypeDisplay(formData.userType || 'normal_user')}
                        </div>
                      )}
                    </div>

                    <div>
                      <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                        角色
                      </label>
                      {isEditing ? (
                        <select
                          value={formData.role || '开发工程师'}
                          onChange={(e) => handleInputChange('role', e.target.value)}
                          className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 dark:bg-gray-800 dark:border-gray-600 dark:text-white"
                        >
                          {roleOptions.map(role => (
                            <option key={role} value={role}>
                              {role}
                            </option>
                          ))}
                        </select>
                      ) : (
                        <div className="px-3 py-2 bg-gray-50 dark:bg-gray-800 rounded-lg text-gray-900 dark:text-white">
                          {formData.role}
                        </div>
                      )}
                    </div>

                    {(formData.userType === 'org_admin' || formData.userType === 'normal_user') && (
                      <div>
                        <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                          所属机构
                        </label>
                        {isEditing ? (
                          <input
                            type="text"
                            value={formData.organization || ''}
                            onChange={(e) => handleInputChange('organization', e.target.value)}
                            className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 dark:bg-gray-800 dark:border-gray-600 dark:text-white"
                            placeholder="请输入所属机构"
                          />
                        ) : (
                          <div className="px-3 py-2 bg-gray-50 dark:bg-gray-800 rounded-lg text-gray-900 dark:text-white">
                            {formData.organization || '未设置'}
                          </div>
                        )}
                      </div>
                    )}

                    <div>
                      <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                        部门
                      </label>
                      {isEditing ? (
                        <input
                          type="text"
                          value={formData.department || ''}
                          onChange={(e) => handleInputChange('department', e.target.value)}
                          className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 dark:bg-gray-800 dark:border-gray-600 dark:text-white"
                          placeholder="请输入部门"
                        />
                      ) : (
                        <div className="px-3 py-2 bg-gray-50 dark:bg-gray-800 rounded-lg text-gray-900 dark:text-white">
                          {formData.department || '未设置'}
                        </div>
                      )}
                    </div>

                    <div>
                      <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                        职位
                      </label>
                      {isEditing ? (
                        <input
                          type="text"
                          value={formData.position || ''}
                          onChange={(e) => handleInputChange('position', e.target.value)}
                          className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 dark:bg-gray-800 dark:border-gray-600 dark:text-white"
                          placeholder="请输入职位"
                        />
                      ) : (
                        <div className="px-3 py-2 bg-gray-50 dark:bg-gray-800 rounded-lg text-gray-900 dark:text-white">
                          {formData.position || '未设置'}
                        </div>
                      )}
                    </div>

                    <div>
                      <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                        状态
                      </label>
                      {isEditing ? (
                        <select
                          value={formData.status || 1}
                          onChange={(e) => handleInputChange('status', parseInt(e.target.value))}
                          className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 dark:bg-gray-800 dark:border-gray-600 dark:text-white"
                        >
                          <option value={1}>启用</option>
                          <option value={0}>停用</option>
                        </select>
                      ) : (
                        <div className="px-3 py-2 bg-gray-50 dark:bg-gray-800 rounded-lg">
                          <span className={`px-2 py-1 text-xs font-medium rounded-full ${
                            formData.status === 1 
                              ? 'bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-300' 
                              : 'bg-red-100 text-red-800 dark:bg-red-900 dark:text-red-300'
                          }`}>
                            {formData.status === 1 ? '启用' : '停用'}
                          </span>
                        </div>
                      )}
                    </div>
                  </div>

                  {/* 密码管理区域 */}
                  {(mode === 'create' || isEditing) && (
                    <div className="mb-6">
                      <div className="flex justify-between items-center mb-3">
                        <label className="block text-sm font-medium text-gray-700 dark:text-gray-300">
                          密码管理
                        </label>
                        <div className="flex space-x-2">
                          <button
                            type="button"
                            onClick={generateRandomPassword}
                            className="px-3 py-1 text-xs bg-blue-600 hover:bg-blue-700 text-white rounded transition-colors"
                          >
                            生成随机密码
                          </button>
                          <button
                            type="button"
                            onClick={resetPassword}
                            className="px-3 py-1 text-xs bg-gray-600 hover:bg-gray-700 text-white rounded transition-colors"
                          >
                            重置为默认
                          </button>
                        </div>
                      </div>
                      <div className="relative">
                        <input
                          type={showPassword ? "text" : "password"}
                          value={formData.password || ''}
                          onChange={(e) => handleInputChange('password', e.target.value)}
                          className="w-full px-3 py-2 pr-10 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 dark:bg-gray-800 dark:border-gray-600 dark:text-white"
                          placeholder="请输入密码"
                        />
                        <button
                          type="button"
                          onClick={() => setShowPassword(!showPassword)}
                          className="absolute right-3 top-1/2 transform -translate-y-1/2 text-gray-500 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-200"
                        >
                          <i className={`fa-solid ${showPassword ? 'fa-eye-slash' : 'fa-eye'}`}></i>
                        </button>
                      </div>
                      {formData.password && (
                        <div className="mt-2 p-2 bg-blue-50 dark:bg-blue-900 rounded border border-blue-200 dark:border-blue-700">
                          <p className="text-xs text-blue-700 dark:text-blue-300">
                            <strong>当前密码：</strong>{formData.password}
                          </p>
                        </div>
                      )}
                      <p className="text-xs text-gray-500 mt-1">
                        {mode === 'create' ? '初始密码将用于首次登录' : '留空表示不修改密码'}
                      </p>
                    </div>
                  )}

                  {/* 最后登录信息（仅查看模式显示） */}
                  {mode === 'view' && user && (
                    <div className="bg-gray-50 dark:bg-gray-800 rounded-lg p-4 mb-6">
                      <h4 className="text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">登录信息</h4>
                      <div className="grid grid-cols-2 gap-4 text-sm">
                        <div>
                          <span className="text-gray-500 dark:text-gray-400">最后登录：</span>
                          <span className="text-gray-900 dark:text-white">{user.lastLogin}</span>
                        </div>
                        <div>
                          <span className="text-gray-500 dark:text-gray-400">用户ID：</span>
                          <span className="text-gray-900 dark:text-white">{user.id}</span>
                        </div>
                      </div>
                    </div>
                  )}
                </div>

                {/* 抽屉底部 */}
                <div className="absolute bottom-0 left-0 right-0 bg-white dark:bg-gray-900 border-t border-gray-200 dark:border-gray-700 p-4 flex justify-between">
                  <div className="flex gap-2">
                    {mode === 'view' && (
                      <button 
                        onClick={() => setIsEditing(true)}
                        className="px-4 py-2 text-sm bg-blue-600 hover:bg-blue-700 text-white rounded-lg transition-colors"
                      >
                        编辑用户
                      </button>
                    )}
                  </div>
                  <div className="flex gap-2">
                    <button 
                      onClick={onClose}
                      className="px-4 py-2 text-sm border border-gray-300 rounded-lg hover:bg-gray-50 dark:border-gray-600 dark:hover:bg-gray-700 transition-colors"
                    >
                      取消
                    </button>
                    {(isEditing || mode === 'create') && (
                      <button 
                        onClick={handleSave}
                        className="px-4 py-2 text-sm bg-green-600 hover:bg-green-700 text-white rounded-lg transition-colors"
                      >
                        {mode === 'create' ? '创建用户' : '保存修改'}
                      </button>
                    )}
                  </div>
                </div>
              </motion.div>
            </div>
          </div>
        </motion.div>
      )}
    </AnimatePresence>
  );
};

export default UserDrawer;